package com.wang.mall.service.impl;

import com.google.code.kaptcha.Producer;
import com.wang.mall.service.SysCaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

@Service
public class SysCaptchaServiceImpl implements SysCaptchaService {

    @Autowired
    private Producer producer;


    @Autowired
    private StringRedisTemplate redisTemplate;


    private static final String LOGIN_CODE_PREFIX = "CODE_PREFIX:";


    /**
     * 获取图片验证码
     *
     * @param uuid
     */
    @Override
    public BufferedImage getCaptcha(String uuid) {
        //生成文字验证码
        String code = producer.createText();

//        SysCaptchaEntity captchaEntity = new SysCaptchaEntity();
//        captchaEntity.setUuid(uuid);
//        captchaEntity.setCode(code);
//        //5分钟后过期
//        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
//        this.save(captchaEntity);

        // 存入redis 5分钟后过期
        redisTemplate.opsForValue().set(LOGIN_CODE_PREFIX + uuid, code, 5, TimeUnit.MINUTES);

        return producer.createImage(code);
    }

    /**
     * 验证码效验
     *
     * @param uuid uuid
     * @param code 验证码
     * @return true：成功  false：失败
     */
    @Override
    public boolean validate(String uuid, String code) {


        // 验证码不存在  或者 验证码过期
        String s = redisTemplate.opsForValue().get(LOGIN_CODE_PREFIX + uuid);
        if (StringUtils.isEmpty(s) || !redisTemplate.hasKey(LOGIN_CODE_PREFIX + uuid)) {
            return false;
        }

        // 验证码存在就校验对不对
        if (code.equals(s)) {
            // 删除验证码
            redisTemplate.delete(LOGIN_CODE_PREFIX + uuid);
            return true;
        }

        return false;
    }
}
